"""
项目管理CLI命令

提供项目创建、管理、剪映草稿生成等命令。
"""

import click
import asyncio
import json
from pathlib import Path
from typing import List, Dict, Any

from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.text import Text

from src.bootstrap import get_service
from src.repositories import ProjectRepository, VideoRepository


console = Console()


class ProjectCommand:
    """项目管理命令类"""
    
    def __init__(self):
        self.project_repo = None
        self.video_repo = None

    def _get_services(self):
        """获取服务实例"""
        if not self.project_repo:
            self.project_repo = get_service(ProjectRepository)
            self.video_repo = get_service(VideoRepository)
    
    def register_commands(self, group):
        """注册命令到组"""
        # 使用内联函数定义Click命令
        @group.command()
        @click.argument('name')
        @click.option('--description', '-d', help='项目描述')
        @click.option('--output-format', default='mp4', help='输出格式')
        @click.option('--width', default=1920, help='画布宽度')
        @click.option('--height', default=1080, help='画布高度')
        @click.option('--fps', default=30.0, help='帧率')
        def create(name, description, output_format, width, height, fps):
            """创建新项目"""
            return self.create_project(name, description, output_format, width, height, fps)

        @group.command()
        @click.option('--active-only', is_flag=True, help='只显示活跃项目')
        @click.option('--limit', '-l', default=20, help='显示数量限制')
        def list(active_only, limit):
            """列出项目"""
            return self.list_projects(active_only, limit)

        @group.command()
        @click.argument('project_id', type=int)
        def info(project_id):
            """显示项目详细信息"""
            return self.show_project_info(project_id)

        @group.command()
        @click.argument('project_id', type=int)
        @click.argument('video_ids', nargs=-1, type=int, required=True)
        def add_videos(project_id, video_ids):
            """添加视频到项目"""
            return self.add_videos_to_project(project_id, video_ids)

        @group.command()
        @click.argument('project_id', type=int)
        @click.argument('video_ids', nargs=-1, type=int, required=True)
        def remove_videos(project_id, video_ids):
            """从项目中移除视频"""
            return self.remove_videos_from_project(project_id, video_ids)

        @group.command()
        @click.argument('project_id', type=int)
        @click.option('--output-dir', '-o', type=click.Path(), required=True, help='输出目录')
        @click.option('--draft-name', '-n', help='草稿名称')
        @click.option('--template', '-t', default='basic', help='剪映模板类型')
        def export_jianying(project_id, output_dir, draft_name, template):
            """导出项目为剪映草稿"""
            return self.export_project_to_jianying(project_id, output_dir, draft_name, template)

        @group.command()
        @click.argument('project_id', type=int)
        @click.argument('new_name')
        def duplicate(project_id, new_name):
            """复制项目"""
            return self.duplicate_project(project_id, new_name)

        @group.command()
        @click.argument('project_id', type=int)
        @click.option('--force', is_flag=True, help='强制删除（不询问确认）')
        def delete(project_id, force):
            """删除项目"""
            return self.delete_project(project_id, force)
    
    def create_project(self, name, description, output_format, width, height, fps):
        """
        创建新项目
        
        NAME: 项目名称
        """
        self._get_services()
        
        console.print(f"📁 创建项目: [cyan]{name}[/cyan]")
        
        try:
            # 检查项目名称是否已存在
            existing = self.project_repo.find_by_name(name)
            if existing:
                console.print(f"❌ 项目名称已存在: {name}", style="red")
                return
            
            # 创建项目设置
            settings_dict = {
                'canvas': {
                    'width': width,
                    'height': height,
                    'fps': fps
                }
            }

            # 序列化设置为JSON字符串
            import json
            settings_json = json.dumps(settings_dict, ensure_ascii=False)

            # 创建项目
            project_data = {
                'name': name,
                'description': description or '',
                'output_format': output_format,
                'settings': settings_json  # 传递JSON字符串而不是字典
            }

            project = self.project_repo.create_from_dict(project_data)
            
            console.print(f"✅ 项目创建成功: [green]{project.name}[/green]")
            console.print(f"   项目ID: {project.id}")
            console.print(f"   输出格式: {project.output_format}")
            console.print(f"   画布尺寸: {width}x{height}")
            console.print(f"   帧率: {fps} fps")
            
        except Exception as e:
            console.print(f"❌ 创建失败: {e}", style="red")
    
    def list_projects(self, active_only, limit):
        """列出项目"""
        self._get_services()
        
        console.print("📋 项目列表")
        
        try:
            if active_only:
                projects = self.project_repo.find_active()
            else:
                projects = self.project_repo.find(limit=limit)
            
            if projects:
                self._display_project_table(projects)
            else:
                console.print("❌ 未找到任何项目", style="yellow")
                
        except Exception as e:
            console.print(f"❌ 查询失败: {e}", style="red")
    
    def _display_project_table(self, projects):
        """显示项目表格"""
        table = Table(title="项目列表", show_header=True, header_style="bold magenta")
        table.add_column("ID", style="dim", no_wrap=True)
        table.add_column("名称", style="cyan")
        table.add_column("视频数", style="green")
        table.add_column("总时长", style="blue")
        table.add_column("输出格式", style="yellow")
        table.add_column("状态", style="white")
        table.add_column("创建时间", style="dim")
        
        for project in projects:
            duration_str = project.total_duration_formatted if project.total_duration else "0s"
            status = "✅ 活跃" if project.is_active else "⏸️  暂停"
            created_str = project.created_at.strftime("%Y-%m-%d") if project.created_at else "未知"
            
            table.add_row(
                str(project.id),
                project.name,
                str(project.video_count),
                duration_str,
                project.output_format,
                status,
                created_str
            )
        
        console.print(table)
    
    def show_project_info(self, project_id):
        """
        显示项目详细信息

        PROJECT_ID: 项目ID
        """
        self._get_services()
        
        try:
            # 获取项目基本信息
            project = self.project_repo.get_by_id(project_id)
            if not project:
                console.print(f"❌ 未找到ID为 {project_id} 的项目", style="red")
                return

            # 获取项目的视频列表
            videos = self.project_repo.get_project_videos(project_id)

            # 获取项目统计信息
            stats = self.project_repo.get_project_statistics(project_id)

            self._display_project_info(project, videos, stats)
            
        except Exception as e:
            console.print(f"❌ 查询失败: {e}", style="red")
    
    def _display_project_info(self, project, videos=None, stats=None):
        """显示项目详细信息"""
        # 基本信息
        info_table = Table(title=f"项目信息 - {project.name}", show_header=False)
        info_table.add_column("属性", style="cyan", no_wrap=True)
        info_table.add_column("值", style="white")
        
        info_table.add_row("ID", str(project.id))
        info_table.add_row("名称", project.name)
        info_table.add_row("描述", project.description or "无")
        info_table.add_row("视频数量", str(project.video_count))
        info_table.add_row("总时长", project.total_duration_formatted)
        info_table.add_row("输出格式", project.output_format)
        info_table.add_row("输出目录", project.output_directory or "未设置")
        info_table.add_row("状态", "✅ 活跃" if project.is_active else "⏸️  暂停")
        info_table.add_row("模板", "✅ 是" if project.is_template else "❌ 否")
        info_table.add_row("创建时间", project.created_at.strftime("%Y-%m-%d %H:%M") if project.created_at else "未知")
        info_table.add_row("更新时间", project.updated_at.strftime("%Y-%m-%d %H:%M") if project.updated_at else "未知")
        
        console.print(info_table)
        
        # 项目设置
        if project.settings:
            settings_text = Text()
            settings_text.append("⚙️  项目设置\n", style="bold")

            # 使用get_settings_dict方法获取设置字典
            settings_dict = project.get_settings_dict()
            canvas = settings_dict.get('canvas', {})
            if canvas:
                settings_text.append(f"画布尺寸: {canvas.get('width', 0)}x{canvas.get('height', 0)}\n")
                settings_text.append(f"帧率: {canvas.get('fps', 0)} fps\n")

            if settings_dict.get('quality'):
                settings_text.append(f"质量设置: {settings_dict['quality']}\n")

            panel = Panel(settings_text, title="设置", border_style="blue")
            console.print(panel)
        
        # 项目视频列表
        if videos:
            video_table = Table(title="项目视频", show_header=True, header_style="bold magenta")
            video_table.add_column("序号", style="dim", no_wrap=True)
            video_table.add_column("文件名", style="cyan")
            video_table.add_column("时长", style="blue")
            video_table.add_column("分辨率", style="yellow")
            video_table.add_column("状态", style="white")

            for i, video in enumerate(videos[:10], 1):  # 只显示前10个
                duration_str = f"{video.duration:.1f}s" if video.duration else "未知"
                resolution = f"{video.width}x{video.height}" if video.width and video.height else "未知"
                status = "✅ 已处理" if getattr(video, 'is_processed', False) else "⏳ 待处理"

                video_table.add_row(
                    str(i),
                    getattr(video, 'file_name', None) or getattr(video, 'filename', None) or f"视频{video.id}",
                    duration_str,
                    resolution,
                    status
                )

            if len(videos) > 10:
                video_table.add_row("...", f"还有 {len(videos) - 10} 个视频", "...", "...", "...")

            console.print(video_table)

        # 统计信息
        if stats:
            stats_table = Table(title="项目统计")
            stats_table.add_column("统计项", style="cyan")
            stats_table.add_column("值", style="white")

            # 格式分布
            format_dist = stats.get('format_distribution', {})
            if format_dist:
                format_str = ", ".join([f"{fmt}: {count}" for fmt, count in format_dist.items()])
                stats_table.add_row("格式分布", format_str)

            # 分辨率分布
            resolution_dist = stats.get('resolution_distribution', {})
            if resolution_dist:
                resolution_str = ", ".join([f"{res}: {count}" for res, count in resolution_dist.items()])
                stats_table.add_row("分辨率分布", resolution_str)

            # 文件大小统计
            if stats.get('total_size'):
                total_size_mb = stats['total_size'] / (1024 * 1024)
                stats_table.add_row("总文件大小", f"{total_size_mb:.1f} MB")

            if stats_table.rows:
                console.print(stats_table)
    
    def add_videos_to_project(self, project_id, video_ids):
        """
        添加视频到项目

        PROJECT_ID: 项目ID
        VIDEO_IDS: 视频ID列表
        """
        self._get_services()
        
        console.print(f"➕ 添加视频到项目 {project_id}")
        
        try:
            # 检查项目是否存在
            project = self.project_repo.get_by_id(project_id)
            if not project:
                console.print(f"❌ 未找到ID为 {project_id} 的项目", style="red")
                return
            
            # 添加视频
            added_count = 0
            failed_count = 0
            
            for video_id in video_ids:
                try:
                    # 检查视频是否存在
                    video = self.video_repo.get_by_id(video_id)
                    if not video:
                        console.print(f"⚠️  视频ID {video_id} 不存在", style="yellow")
                        failed_count += 1
                        continue
                    
                    # 添加到项目
                    success = self.project_repo.add_video_to_project(project_id, video_id)
                    if success:
                        console.print(f"✅ 添加视频: {video.file_name}")
                        added_count += 1
                    else:
                        console.print(f"⚠️  视频已存在于项目中: {video.file_name}", style="yellow")
                        failed_count += 1
                        
                except Exception as e:
                    console.print(f"❌ 添加视频 {video_id} 失败: {e}", style="red")
                    failed_count += 1
            
            console.print(f"\n📊 添加结果: 成功 {added_count}, 失败 {failed_count}")
            
        except Exception as e:
            console.print(f"❌ 操作失败: {e}", style="red")
    
    def remove_videos_from_project(self, project_id, video_ids):
        """
        从项目中移除视频
        
        PROJECT_ID: 项目ID
        VIDEO_IDS: 视频ID列表
        """
        self._get_services()
        
        console.print(f"➖ 从项目 {project_id} 移除视频")
        
        try:
            # 检查项目是否存在
            project = self.project_repo.get_by_id(project_id)
            if not project:
                console.print(f"❌ 未找到ID为 {project_id} 的项目", style="red")
                return
            
            # 移除视频
            removed_count = 0
            failed_count = 0
            
            for video_id in video_ids:
                try:
                    success = self.project_repo.remove_video_from_project(project_id, video_id)
                    if success:
                        console.print(f"✅ 移除视频ID: {video_id}")
                        removed_count += 1
                    else:
                        console.print(f"⚠️  视频ID {video_id} 不在项目中", style="yellow")
                        failed_count += 1
                        
                except Exception as e:
                    console.print(f"❌ 移除视频 {video_id} 失败: {e}", style="red")
                    failed_count += 1
            
            console.print(f"\n📊 移除结果: 成功 {removed_count}, 失败 {failed_count}")
            
        except Exception as e:
            console.print(f"❌ 操作失败: {e}", style="red")
    
    def export_project_to_jianying(self, project_id, output_dir, draft_name, template):
        """
        导出项目为剪映草稿
        
        PROJECT_ID: 项目ID
        """
        self._get_services()
        
        console.print(f"🎬 导出项目 {project_id} 为剪映草稿")
        
        try:
            # 获取项目和视频
            project = self.project_repo.get_with_videos(project_id)
            if not project:
                console.print(f"❌ 未找到ID为 {project_id} 的项目", style="red")
                return
            
            if not hasattr(project, 'videos') or not project.videos:
                console.print("❌ 项目中没有视频", style="yellow")
                return
            
            # 获取视频文件路径
            video_files = [video.file_path for video in project.videos if video.is_available]
            
            if not video_files:
                console.print("❌ 项目中没有可用的视频文件", style="yellow")
                return
            
            console.print(f"📁 找到 {len(video_files)} 个可用视频")
            
            # 创建简化的剪映项目数据
            if not draft_name:
                draft_name = f"{project.name}_draft"

            # 创建输出目录
            output_path = Path(output_dir)
            output_path.mkdir(parents=True, exist_ok=True)

            # 创建草稿目录
            draft_dir = output_path / draft_name
            draft_dir.mkdir(exist_ok=True)

            # 生成简化的项目文件
            project_data = {
                'name': project.name,
                'version': '1.0.0',
                'canvas': {
                    'width': project.settings.get('canvas', {}).get('width', 1920) if project.settings else 1920,
                    'height': project.settings.get('canvas', {}).get('height', 1080) if project.settings else 1080,
                    'fps': project.settings.get('canvas', {}).get('fps', 30.0) if project.settings else 30.0
                },
                'materials': [{'file_path': vf, 'type': 'video'} for vf in video_files],
                'tracks': [{'type': 'video', 'clips': video_files}]
            }

            project_file = draft_dir / "project.json"
            with open(project_file, 'w', encoding='utf-8') as f:
                json.dump(project_data, f, indent=2, ensure_ascii=False)

            console.print(f"✅ 剪映草稿已生成: [green]{draft_dir}[/green]")
            console.print(f"   项目文件: {project_file}")
            console.print(f"   视频数量: {len(video_files)}")
            console.print(f"   画布尺寸: {project_data['canvas']['width']}x{project_data['canvas']['height']}")
            
        except Exception as e:
            console.print(f"❌ 导出失败: {e}", style="red")
    

    
    def duplicate_project(self, project_id, new_name):
        """
        复制项目
        
        PROJECT_ID: 源项目ID
        NEW_NAME: 新项目名称
        """
        self._get_services()
        
        console.print(f"📋 复制项目 {project_id} 为: [cyan]{new_name}[/cyan]")
        
        try:
            # 检查新名称是否已存在
            existing = self.project_repo.find_by_name(new_name)
            if existing:
                console.print(f"❌ 项目名称已存在: {new_name}", style="red")
                return
            
            # 复制项目
            new_project = self.project_repo.duplicate_project(project_id, new_name)
            
            if new_project:
                console.print(f"✅ 项目复制成功: [green]{new_project.name}[/green]")
                console.print(f"   新项目ID: {new_project.id}")
                console.print(f"   视频数量: {new_project.video_count}")
                console.print(f"   总时长: {new_project.total_duration_formatted}")
            else:
                console.print(f"❌ 未找到ID为 {project_id} 的项目", style="red")
            
        except Exception as e:
            console.print(f"❌ 复制失败: {e}", style="red")
    
    def delete_project(self, project_id, force):
        """
        删除项目
        
        PROJECT_ID: 项目ID
        """
        self._get_services()
        
        try:
            # 检查项目是否存在
            project = self.project_repo.get_by_id(project_id)
            if not project:
                console.print(f"❌ 未找到ID为 {project_id} 的项目", style="red")
                return
            
            # 确认删除
            if not force:
                console.print(f"⚠️  即将删除项目: [yellow]{project.name}[/yellow]")
                console.print(f"   项目ID: {project.id}")
                console.print(f"   视频数量: {project.video_count}")
                
                if not click.confirm("确定要删除此项目吗？"):
                    console.print("❌ 操作已取消", style="yellow")
                    return
            
            # 删除项目
            success = self.project_repo.delete(project_id)
            
            if success:
                console.print(f"✅ 项目已删除: [green]{project.name}[/green]")
            else:
                console.print("❌ 删除失败", style="red")
            
        except Exception as e:
            console.print(f"❌ 删除失败: {e}", style="red")
